package crp.core.security.domain.services;

import crp.core.security.domain.models.AccessToken;
import crp.core.security.domain.services.token.AccessTokenBuilder;
import io.quarkus.security.credential.PasswordCredential;
import io.quarkus.security.identity.IdentityProviderManager;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.AuthenticationRequest;
import io.quarkus.security.identity.request.UsernamePasswordAuthenticationRequest;
import lombok.extern.slf4j.Slf4j;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
@Slf4j
public class BasicAuthenticator {
    private final IdentityProviderManager identityProviderManager;
    private final AccessTokenBuilder accessTokenBuilder;

    @Inject
    public BasicAuthenticator(IdentityProviderManager identityProviderManager,
                              AccessTokenBuilder accessTokenBuilder) {
        this.identityProviderManager = identityProviderManager;
        this.accessTokenBuilder = accessTokenBuilder;
    }

    public AccessToken authenticate(String username, String password) {
        AuthenticationRequest request = new UsernamePasswordAuthenticationRequest(username,
                new PasswordCredential(password.toCharArray()));
        LOGGER.info("usernaem:{},password:{}", username, password);
        SecurityIdentity securityIdentity = identityProviderManager.authenticateBlocking(request);
        LOGGER.info("roles:{}", securityIdentity.getRoles());
        return accessTokenBuilder.create(securityIdentity);
    }
}
